import router from '@/router';
// @ts-ignore
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import setting from '@/setting'
import pinia from '@/store';
import useUserStore from '@/store/modules/user'
const userStore = useUserStore(pinia)

router.beforeEach(async(to:any, from:any, next:any) => {
    document.title = `${setting.title} - ${to.meta.title}`
    nprogress.start();
    const token = userStore.token
    const username = userStore.username
   
    // 有token
    if(token){
       if(to.path=='/login'){
        next({path:'/'})
       }else{
        // 有用户名
        if(username){
            next()
        }else{
            try {
                // 获取用户信息
                await userStore.userInfo()
                 //万一:刷新的时候是异步路由,有可能获取到用户信息、异步路由还没有加载完毕,出现空白的效果
                next({...to})
            } catch (error) {
                // token过期
                userStore.avatar = '',
                userStore.username = '',
                userStore.token = ''
                localStorage.removeItem('TOKEN')
                next({path:'/login',query:{redirect: to.path}})
            }
        }
       }
    }else{
        if(to.path=='/login'){
            next()
        }else{
            next({ path: '/login', query: { redirect: to.path } })
        }
        
    }
    
})
router.afterEach((to:any, from:any) => {
    nprogress.done()
    
});